package com.ygqh.baby.controller.mobile;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.model.PrizeItem.Type;
import com.ygqh.baby.model.YgOrderInfoModel;
import com.ygqh.baby.po.*;
import com.ygqh.baby.service.*;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.SessionUtil;
import com.ygqh.baby.utils.ThreadPool;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 转盘抽奖活动相关
 *
 * @author jiangyunbo
 */
@Controller
@RequestMapping("/mobile/action")
public class YgActionController {

    protected final Logger logger = Logger.getLogger(this.getClass());
    // 抽奖的redis key
    private static final String Rotate = "Rotate_child_";
    private static final int oneDay = 24 * 60 * 60 * 1000;
    @Autowired
    private YgCouponService ygCouponService;
    @Autowired
    private com.ygqh.baby.redis.RedisDao redisDao;
    @Autowired
    private YgActionAddressService actionAddressService;
    @Autowired
    private YgUserBalanceService userBalanceService;

    @Autowired
    private YgCouponUseDetailService couponUseDetailService;

    @Autowired
    private YgUserService userService;
    @Autowired
    private YgCouponDetailService ygCouponDetailService;

    @Autowired
    private YgUserBalanceDetailService userBalanceDetailService;
    @Autowired
    private YgOrderService orderService;
    @Autowired
    private ThreadPool threadPool;
    @Autowired
    private YgCardCouponService ygCardCouponService;
    @Autowired
    private YgCardCouponDetailService ygCardCouponDetailService;

    @RequestMapping(value = "saveAddress", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject saveAddress(String callback, Long id, String receiver, String telPhone, String provinceName, String cityName, String areaName,
                                   String address) throws ParseException {
        YgActionAddress actionAddress = actionAddressService.findById(id);
        if (actionAddress == null)
            return new JSONPObject(callback, Message.error(""));

        Long userId = SessionUtil.getCurrentUser().getId();
        if (!actionAddress.getUserId().equals(userId))
            return new JSONPObject(callback, Message.error("用户验证失败"));

        actionAddress.setReceiver(receiver);
        actionAddress.setTelphone(telPhone);
        actionAddress.setAddress(provinceName + "," + cityName + "," + areaName + "," + address);
        actionAddressService.update(actionAddress);
        this.syncActionOrder(actionAddress.getId());
        return new JSONPObject(callback, Message.success(""));
    }

    private void syncActionOrder(Long addId) {
        threadPool.getExecutorService().execute(new Runnable() {

            @Override
            public void run() {
                Message message = actionAddressService.syncAction(addId);
                if (message.getType().equals(Message.Type.error)) {
                    logger.info("同步赠品订单失败，" + message.getContent());
                }
            }
        });

    }

    /**
     * 转盘抽奖
     *
     * @param callback
     * @return
     * @throws ParseException
     */
    @SuppressWarnings("deprecation")
    @RequestMapping(value = "getRotateInfo", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject getRotateInfo(String callback) throws ParseException {
        // Object[][] prizeArr = new Object[][]{
        // //里面的指针转动
        // {0,0,0,"谢谢惠顾！","0.1"},
        // {1,1,0,"赠送布偶熊","34"},
        // {2,192,50,"50元现金券","5"},
        // {3,0,500,"500元现金券","0"},
        // {4,193,200,"满800减200优惠券","20.9"},
        // {5,186,120,"满500减120券","25"},
        // {6,194,400,"满1200减400优惠券","15"}
        //
        // };

        Object[][] prizeArr = new Object[][]{
                // 里面的指针转动
                {0, 0, 0, "谢谢惠顾！", "30"}, {1, 1, 0, "赠送布偶熊", "0.1"}, {2, 70, 50, "50元现金券", "2"}, {3, 0, 500, "500元现金券", "0"},
                {4, 71, 200, "满800减200优惠券", "24.9"}, {5, 72, 120, "满500减120券", "26"}, {6, 73, 400, "满1200减400优惠券", "17"}

        };
        JSONPObject json = null;
        // 判断活动时间
        Date actionDate;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        actionDate = df.parse("2017-1-5");
        Date currDate = new Date();
        /*
         * if(currDate.before(actionDate)){ json=new JSONPObject(callback,
         * Message.error("此活动还未开始")); return json;
         *
         * }
         */
        if (currDate.after(actionDate)) {
            json = new JSONPObject(callback, Message.error("此活动已经结束"));
            return json;
        }
        // 根据用户id 从redis 中判断 是否含有参与机会
        YgUser user = SessionUtil.getCurrentUser();
        String key = Rotate + user.getId() + "_" + currDate.getDay();
        String val = redisDao.get(key);
        if (val != null && Integer.valueOf(val) >= 3) {
            json = new JSONPObject(callback, Message.error("不要贪心,每天最多抽3次哦"));
            return json;
        }
        List<Double> orignalRates = new ArrayList<>();
        for (int i = 0; i < prizeArr.length; i++) {
            String str = (String) prizeArr[i][4];
            orignalRates.add(Double.valueOf(str));
        }
        Integer selectId = lottery(orignalRates);

        if (selectId < 7)// 设置用户的优惠券
        {
            if (selectId == 0) {
                json = new JSONPObject(callback, Message.success("很遗憾，您没有中奖，再接再厉", 0));
            } else if (selectId == 1) {

                String strDate = DateConvertUtils.format(new Date(), "yyyy-MM-dd");
                String bearKey = Rotate + "bear_" + strDate;
                String bearVal = redisDao.get(bearKey);
                if (bearVal == null) {
                    redisDao.set(bearKey, "1", oneDay);
                } else {
                    Integer bearCount = Integer.valueOf(bearVal);
                    if (bearCount > 10) {
                        return new JSONPObject(callback, Message.success("很遗憾，您没有中奖，再接再厉", 0));
                    } else {
                        YgActionAddress actionAddress = new YgActionAddress();
                        actionAddress.setCreateTime(new Date());
                        actionAddress.setUserId(SessionUtil.getCurrentUser().getId());
                        actionAddressService.save(actionAddress);
                        bearCount++;
                        redisDao.set(bearKey, bearCount + "", oneDay);
                        return new JSONPObject(callback, Message.success(actionAddress.getId() + "", 10));
                    }

                }
                json = new JSONPObject(callback, Message.success(prizeArr[selectId][2]));

            } else {

                Long couponBatchId = Long.valueOf(prizeArr[selectId][1].toString());
                ygCouponService.receiveCoupon(couponBatchId, user);
                json = new JSONPObject(callback, Message.success(prizeArr[selectId][2]));
            }
            // 设置次数
            Integer num = val == null ? 1 : Integer.valueOf(val) + 1;
            redisDao.set(key, num.toString(), oneDay);

        }

        return json;
    }

    private static final Integer DAY_COUNT = 3; // 每日抽次数

    // private static final Integer DAY_COUNT = 3000; //每日抽次数
    // private static final Integer BEAR_COUNT = 500; //咕咕鸡个数
    // private static final Integer DAY_PRICE = 3000; //每天红包预算
    // private static final Integer RED_COUNT = 1300; //8.8红包次数

    /**
     * 摇一摇
     *
     * @param callback
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "shake", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject shake(String callback) throws ParseException {
        Object[][] prizeArr = new Object[][]{
                // 里面的指针转动
                {0, 0, 0, "六一快乐！", "32"}, {1, 145, 15, "15元现金券", "8"}, {2, 144, 10, "10元现金券", "15"}, {3, 143, 5, "5元无门槛券", "27"},
                {4, 0, 6.1, "6.1元红包", "0.5"}, {5, 0, 0.61, "0.61元红包", "12"}, {6, 0, 1.61, "1.61元红包", "5.5"}

                // {0, 0, 0, "新春好运！", "10"},
                // {1, 0, 1, "一只咕咕鸡", "30"},
                // {2, 192, 50, "50元现金券", "30"},
                // {3, 196, 60, "满300减60元", "10"},
                // {4, 193, 200, "满800减200优惠券", "19"},
                // {5, 186, 120, "满500减120券", "19"},
                // {6, 0, 8.88, "8.88元红包", "30"},
                // {7, 0, 0.88, "0.88元红包", "30"},

        };
        JSONPObject json;
        // 判断活动时间
        Date actionDate;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        actionDate = df.parse("2017-6-9");
        Date currDate = new Date();
        if (currDate.after(actionDate)) {
            json = new JSONPObject(callback, Message.error("此活动已经结束"));
            return json;
        }

        String strDate = DateConvertUtils.format(new Date(), "yyyy-MM-dd");
        String userKey = Rotate + SessionUtil.getCurrentUser().getUserName() + strDate;
        String userVal = redisDao.get(userKey);
        Integer userCount = 0;
        if (userVal == null) {
            userCount = 1;
            redisDao.set(userKey, userCount + "", oneDay);
        } else {
            userCount = Integer.valueOf(userVal);
            userCount++;
            redisDao.set(userKey, userCount + "", oneDay);
        }
        YgUser user = SessionUtil.getCurrentUser();
        // 每天最多抽3次
        if (userCount > DAY_COUNT) {
            json = new JSONPObject(callback, Message.error(generateResultMap(userCount, "不要贪心,每天最多抽3次哦")));
            return json;
        }
        List<Double> orignalRates = new ArrayList<>();
        for (int i = 0; i < prizeArr.length; i++) {
            String str = (String) prizeArr[i][4];
            orignalRates.add(Double.valueOf(str));
        }
        Integer selectId = lottery(orignalRates);

        if (selectId < 4)// 设置用户的优惠券
        {
            if (selectId == 0) {
                json = new JSONPObject(callback, Message.success(prizeArr[selectId][3].toString(), generateResultMap(userCount, prizeArr[selectId][2])));
            } else {

                Long couponBatchId = Long.valueOf(prizeArr[selectId][1].toString());
                ygCouponService.receiveCoupon(couponBatchId, user);
                json = new JSONPObject(callback, Message.success(generateResultMap(userCount, prizeArr[selectId][2])));
            }

        } else {

            userBalanceService.backAcountPrice(user.getId(), new BigDecimal(prizeArr[selectId][2].toString()));

            YgUserBalanceDetail ygUserBalanceDetail = new YgUserBalanceDetail();
            ygUserBalanceDetail.setUserId(user.getId());
            ygUserBalanceDetail.setBalancePrice(new BigDecimal(prizeArr[selectId][2].toString()));
            ygUserBalanceDetail.setPriceType(BalanceType.Balance);
            ygUserBalanceDetail.setOperation(OperationType.Activity.getTitle());
            ygUserBalanceDetail.setOperationType(OperationType.Activity);
            ygUserBalanceDetail.setCreateTime(new Date());
            ygUserBalanceDetail.setRemark("领取活动礼包");
            userBalanceDetailService.save(ygUserBalanceDetail);

            json = new JSONPObject(callback, Message.success(generateResultMap(userCount, prizeArr[selectId][2])));

        }

        return json;
    }

    @RequestMapping(value = "useCoupon", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject useCoupon(String shareSourceCode, String orderId, String callback) throws ParseException {
        JSONPObject json = null;
        /**
         * 判断分享人是否存在
         */
        if (shareSourceCode == null || shareSourceCode.equals("") || shareSourceCode.equals("null")) {
            return new JSONPObject(callback, Message.error("0011"));
        }
        YgUser shareUser = userService.findBySourceCode(shareSourceCode);
        if (shareUser == null) {
            return new JSONPObject(callback, Message.error("0011"));
        }

        /**
         * 判断是否领取过奖励
         */
        Long userId = SessionUtil.getCurrentUser().getId();
        YgCouponUseDetail couponUseDetail = null;
        if (orderId == null) {
            /**
             * 判断是否领过好友分享
             */
            List<YgCouponUseDetail> list = couponUseDetailService.findCouponUseDetailByShareUserId(userId, shareUser.getId());
            if (CollectionUtils.isEmpty(list)) {
                return new JSONPObject(callback, Message.error("0012"));
            }
            couponUseDetail = list.get(0);
        } else {

            /**
             * 判断订单是否是真实存在
             */
            YgOrderInfoModel orderInfo = orderService.findOrderInfo(Long.parseLong(orderId), shareUser.getId());
            if (orderInfo == null) {
                return new JSONPObject(callback, Message.error("0013"));
            }

            /**
             * 判断是否领取过订单分享
             */
            couponUseDetail = couponUseDetailService.findCouponUseDetailByOrderId(userId, orderId);
            if (couponUseDetail != null) {
                return new JSONPObject(callback, Message.error("0014"));
            }

        }
        /**
         * 设置的奖项
         */
        // Object[][] prizeArr = new Object[][]{
        // {0,1,"一元成长基金", "15"},
        // {1,2,"二元成长基金", "30"},
        // {2,5,"五元成长基金", "1"},
        // {3,207,"五元现金卷", "10"},
        // {4,208,"十元现金卷", "4"},
        // {5,209,"满一百减五元优惠劵","35"},
        // {6,210, "满一百减十元优惠劵","10"}
        // };

        /**
         * 正式环境奖项
         */
        Object[][] prizeArr = new Object[][]{{0, 1, "一元成长基金", "15"}, {1, 2, "二元成长基金", "5"}, {2, 5, "五元成长基金", "1"}, {3, 128, "五元现金卷", "10"},
                {4, 129, "十元现金卷", "4"}, {5, 126, "满一百减五元优惠劵", "35"}, {6, 125, "满一百减十元优惠劵", "30"}};

        /**
         * 随机一个奖项数
         */

        List<Double> orignalRates = new ArrayList<>();
        for (int i = 0; i < prizeArr.length; i++) {
            String str = (String) prizeArr[i][3];
            orignalRates.add(Double.valueOf(str));
        }
        Integer selectId = lottery(orignalRates);
        String msg = couponUseDetailService.saveUseCoupon(selectId, prizeArr, SessionUtil.getCurrentUser(), orderId, shareUser);
        json = new JSONPObject(callback, Message.success(msg));

        return json;
    }

    @RequestMapping(value = "shareAccount", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject shareAccount(String callback) throws ParseException {
        JSONPObject json = null;
        int selectId = 0;
        BigDecimal money = new BigDecimal(0);
        // 判断用户是否是新用户
        YgUser user = SessionUtil.getCurrentUser();
        if (redisDao.get("share_account" + user.getId()) != null) {
            return new JSONPObject(callback, Message.error("不要贪心,您已参与过活动", null));
        }
        /*
         * if(user.getId().intValue()<1000){ json=new JSONPObject(callback,
         * Message.success(generateResultMap(1,1))); selectId=1; money=new
         * BigDecimal(1); }else{
         */
        Object[][] prizeArr = new Object[][]{{0, 3, "三元成长基金", "45"}, {1, 5, "五元成长基金", "35"}, {2, 6.66, "6.66元成长基金", "13"}, {3, 10, "10元现金卷", "6"},
                {4, 49, "四十九元现金卷", "1"}};

        /**
         * 随机一个奖项数
         */

        List<Double> orignalRates = new ArrayList<>();
        for (int i = 0; i < prizeArr.length; i++) {
            String str = (String) prizeArr[i][3];
            orignalRates.add(Double.valueOf(str));
        }
        selectId = lottery(orignalRates);
        money = new BigDecimal(prizeArr[selectId][1].toString());
        // }
        userBalanceService.backAcountPrice(user.getId(), money);
        YgUserBalanceDetail ygUserBalanceDetail = new YgUserBalanceDetail();
        ygUserBalanceDetail.setUserId(user.getId());
        ygUserBalanceDetail.setBalancePrice(money);
        ygUserBalanceDetail.setPriceType(BalanceType.Balance);
        ygUserBalanceDetail.setOperation(OperationType.Activity.getTitle());
        ygUserBalanceDetail.setOperationType(OperationType.Activity);
        ygUserBalanceDetail.setCreateTime(new Date());
        ygUserBalanceDetail.setRemark("领取活动礼包");
        userBalanceDetailService.save(ygUserBalanceDetail);
        redisDao.set("share_account" + user.getId(), "1", 0);
        json = new JSONPObject(callback, Message.success(generateResultMap(1, money)));

        return json;
    }

    @RequestMapping(value = "turnTable11", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject turnTable11(String callback) throws ParseException {
        Integer selectId = 0;
        // 判断用户是否是新用户
        YgUser user = SessionUtil.getCurrentUser();
        String format = DateConvertUtils.format(new Date());
        String baseKey = "turnTable11_" + format;

        Date validDate = DateConvertUtils.parse("2017-12-31", DateConvertUtils.DATE_FORMAT);
        Date now = DateConvertUtils.getDateStart(new Date());
        if (now.after(validDate)) {
            return new JSONPObject(callback, Message.error("活动已结束", null));
        }
        if (redisDao.get(baseKey + "_" + user.getId()) != null) {
            return new JSONPObject(callback, Message.error("不要贪心,您已参与过活动,请明天再来", null));
        }
        /**
         *
         * 帆布包，0.5%，限量100个 沙发，0.1%，限量5个 999-150，10% 400-50，10% 10元券，5% 1元成长金
         * 剩余比例 5元成长金 5% 9元成长金 0.5% 49元成长金 0.1% 限量10个 谢谢惠顾5%
         */

        Object[][] prizeArr = new Object[][]{{0, 1, "1元成长金", "54"}, {0, 5, "5元成长金", "2"}, {0, 9, "9元成长金", "0.5"}, {1, 49, "49元成长金", "0.1"},
                // { 0, 320, "谢谢回顾", "0.1" },
                {5, 500605031, "帆布包", "0.2"}, {5, 500779011, "熊玩偶", "0.2"}, {0, 227, "200-30", "2"}, {0, 195, "400-50", "40"},
                {0, 216, "10元券", "1"}};

        /**
         * 随机一个奖项数
         */

        List<Double> orignalRates = new ArrayList<>();
        for (int i = 0; i < prizeArr.length; i++) {
            String str = (String) prizeArr[i][3];
            orignalRates.add(Double.valueOf(str));
        }
        selectId = lottery(orignalRates);
        // selectId = selectId == 5 ? 4 : selectId;
        Long addrId = this.givePrize(selectId, prizeArr, user, baseKey);
        selectId = addrId == -1L ? 0 : selectId;
        redisDao.set(baseKey + "_" + user.getId(), "1", 24 * 60 * 60 * 1000);
        return new JSONPObject(callback, Message.success(addrId.toString(), prizeArr[selectId][1].toString()));

    }

    @RequestMapping(value = "turnTable12", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject turnTable12(String callback) throws ParseException {
        YgUser user = SessionUtil.getCurrentUser();
        String format = DateConvertUtils.format(new Date());
        String baseKey = "turnTable12_" + format;

        Date startDate = DateConvertUtils.parse("2018-10-30", DateConvertUtils.DATE_FORMAT);
        Date endDate = DateConvertUtils.parse("2018-11-13", DateConvertUtils.DATE_FORMAT);
        Date now = DateConvertUtils.getDateStart(new Date());
        if (now.before(startDate)) {
            return new JSONPObject(callback, Message.error("活动未开始", null));
        }
        if (now.after(endDate)) {
            return new JSONPObject(callback, Message.error("活动已结束", null));
        }
        if (redisDao.get(baseKey + "_" + user.getId()) != null) {
            return new JSONPObject(callback, Message.error("不要贪心,您已参与过活动,请明天再来", null));
        }
        Object[][] prizeArr;
        /**
         * 判断用户是否是新客
         */
        Boolean newCustom = userService.isNewCustom(user.getId());
        // 测试
		/*if (newCustom) { // 新客奖品池
			prizeArr = new Object[][] {
				{ 1, 1, "1元", "26", Type.Balance, 420, 30 },
				{ 2, 5, "5元", "10", Type.Balance, 140, 10 },
				{ 3, 9, "9元", "2", Type.Balance, 70, 5 },
				{ 4, 49, "49元", "0.5", Type.Balance, 14, 1 },
				{ 5, 1111, "1111元", "0", Type.Cash, 0, 0 },
				{ 6, 316, "21-20优惠券", "30", Type.Coupon, 10000, null },
				{ 7, 317, "200-30优惠券", "20", Type.Coupon, 10000, null },
				{ 8, 318, "400-80优惠券", "10", Type.Coupon, null, null },
				{ 9, 68, "双肩帆布包", "0.5", Type.Goods, 140, 10 },
				{ 10, 70, "粉色猫咪玩偶", "1", Type.Goods, 70, 5 }
			};
		} else { // 老客奖品池
			prizeArr = new Object[][] {
				{ 1, 1, "1元", "26.5", Type.Balance, 420, 30 },
				{ 2, 5, "5元", "10", Type.Balance, 140, 10 },
				{ 3, 9, "9元", "2", Type.Balance, 70, 5 },
				{ 4, 49, "49元", "0", Type.Balance, 14, 1 },
				{ 5, 1111, "1111元", "0", Type.Cash, 0, 0 },
				{ 6, 316, "21-20优惠券", "5", Type.Coupon, 10000, null },
				{ 7, 317, "200-30优惠券", "5", Type.Coupon, 10000, null },
				{ 8, 318, "400-80优惠券", "50", Type.Coupon, null, null },
				{ 9, 68, "双肩帆布包", "0.5", Type.Goods, 140, 10 },
				{ 10, 70, "粉色猫咪玩偶", "1", Type.Goods, 70, 5 }
			};
		}*/
        // 正式
        if (newCustom) { // 新客奖品池
            prizeArr = new Object[][]{
                    {1, 1, "1元", "26", Type.Balance, 420, 30},
                    {2, 5, "5元", "10", Type.Balance, 140, 10},
                    {3, 9, "9元", "2", Type.Balance, 70, 5},
                    {4, 49, "49元", "0.5", Type.Balance, 14, 1},
                    {5, 1111, "1111元", "0", Type.Cash, 0, 0},
                    {6, 346, "21-20优惠券", "30", Type.Coupon, 10000, null},
                    {7, 347, "200-30优惠券", "20", Type.Coupon, 10000, null},
                    {8, 348, "400-80优惠券", "10", Type.Coupon, null, null},
                    {9, 75, "双肩帆布包", "0.5", Type.Goods, 140, 10},
                    {10, 73, "粉色猫咪玩偶", "1", Type.Goods, 70, 5}
            };
        } else { // 老客奖品池
            prizeArr = new Object[][]{
                    {1, 1, "1元", "26.5", Type.Balance, 420, 30},
                    {2, 5, "5元", "10", Type.Balance, 140, 10},
                    {3, 9, "9元", "2", Type.Balance, 70, 5},
                    {4, 49, "49元", "0", Type.Balance, 14, 1},
                    {5, 1111, "1111元", "0", Type.Cash, 0, 0},
                    {6, 346, "21-20优惠券", "5", Type.Coupon, 10000, null},
                    {7, 347, "200-30优惠券", "5", Type.Coupon, 10000, null},
                    {8, 348, "400-80优惠券", "50", Type.Coupon, null, null},
                    {9, 75, "双肩帆布包", "0.5", Type.Goods, 140, 10},
                    {10, 73, "粉色猫咪玩偶", "1", Type.Goods, 70, 5}
            };
        }

        Integer selectId = 0;

        // 默认奖项
        Integer defaultSelectId = 7;

        /*
         * 随机一个奖项数
         */
        List<Double> orignalRates = new ArrayList<>();
        for (Object[] aPrizeArr : prizeArr) {
            String str = (String) aPrizeArr[3];
            orignalRates.add(Double.valueOf(str));
        }
        selectId = lottery(orignalRates);
        /*
         * 处理抽奖结果
         */
        boolean isDefault = false;
        if (prizeArr[selectId][5] != null) {
            // 有总数量限制，需要验证已发总数量
            String value = redisDao.get("turnTable12_giveCount_" + prizeArr[selectId][0]);
            Integer totalCount = Integer.valueOf(prizeArr[selectId][5].toString());
            // 已发数量达到峰值
            if (StringUtils.isNotBlank(value) && Integer.valueOf(value).compareTo(totalCount) >= 0) {
                isDefault = true;
            }
        }
        if (!isDefault && prizeArr[selectId][6] != null) {
            // 有每日数量限制，需要验证当日已发数量
            String value = redisDao.get(baseKey + "_giveCount_" + prizeArr[selectId][0]);
            Integer totalCount = Integer.valueOf(prizeArr[selectId][6].toString());
            // 当日已发数量达到峰值
            if (StringUtils.isNotBlank(value) && Integer.valueOf(value).compareTo(totalCount) >= 0) {
                isDefault = true;
            }
        }
        if (isDefault) {
            selectId = defaultSelectId;
        }
        Type type = (Type) prizeArr[selectId][4];
        switch (type) {
            case Balance: // 成长基金
                this.addBalance(user.getId(), new BigDecimal(prizeArr[selectId][1].toString()));
                break;
            case Coupon: // 优惠券
                Long couponId = Long.parseLong(prizeArr[selectId][1].toString());
                ygCouponDetailService.receiveCouponWithRemark(couponId, "转盘抽奖", user);
                break;
            case Goods: // 实物
                Message message = ygCardCouponDetailService.generateCardCoupon(user.getId(), Long.parseLong(prizeArr[selectId][1].toString()), null, baseKey);
                if (!Message.isSuccess(message)) {
                    isDefault = true;
                }
                break;
            case Cash: // 暂无现金红包
            default:
                /*
                 *  默认赠予
                 */
                isDefault = true;
                break;
        }

        if (isDefault) {
            selectId = defaultSelectId;
            type = (Type) prizeArr[selectId][4];
            if (Type.Balance.equals(type)) {
                this.addBalance(user.getId(), new BigDecimal(prizeArr[selectId][1].toString()));
            } else if (Type.Coupon.equals(type)) {
                ygCouponDetailService.receiveCouponWithRemark(Long.parseLong(prizeArr[selectId][1].toString()), "转盘抽奖", user);
            }
        }

        redisDao.set(baseKey + "_" + user.getId(), "1", 24 * 60 * 60 * 1000);
        if (prizeArr[selectId][5] != null) {
            // 有总数量限制， 更新已领取总数量
            String key = "turnTable12_giveCount_" + prizeArr[selectId][0];
            String value = redisDao.get(key);
            if (StringUtils.isNotBlank(value)) {
                value = (Integer.valueOf(value) + 1) + "";
            } else {
                value = "1";
            }
            long expire = DateConvertUtils.addDay(endDate, 1).getTime();
            redisDao.set(key, value, expire);
            logger.info("转盘活动：【" + prizeArr[selectId][2].toString() + "】已被领取" + value + "个");
        }
        if (prizeArr[selectId][6] != null) {
            // 有每日数量限制， 更新已领取每日数量
            String key = baseKey + "_giveCount_" + prizeArr[selectId][0];
            String value = redisDao.get(key);
            if (StringUtils.isNotBlank(value)) {
                value = (Integer.valueOf(value) + 1) + "";
            } else {
                value = "1";
            }
            redisDao.set(key, value, 24 * 60 * 60 * 1000);
            logger.info("转盘活动：【" + prizeArr[selectId][2].toString() + "】今日已被领取" + value + "个");
        }

        return new JSONPObject(callback, Message.success("0", prizeArr[selectId][0]));
    }

    private int addBalance(Long userId, BigDecimal money) {
        userBalanceService.backAcountPrice(userId, money);
        userBalanceDetailService.addBalanceDetail(userId, money, BalanceType.Balance, OperationType.Activity, "领取活动礼包");
        return 1;

    }

    ;

    private Long addActionAddress(String skuCode, String remark) {

        YgActionAddress actionAddress = new YgActionAddress();
        actionAddress.setCreateTime(new Date());
        actionAddress.setUserId(SessionUtil.getCurrentUser().getId());
        actionAddress.setSkuCode(skuCode);
        actionAddress.setRemark(remark);
        actionAddressService.save(actionAddress);
        return actionAddress.getId();

    }

    /**
     * @param couponId
     * @param user
     * @param date     优惠券有效期
     * @return int 返回类型
     * @throws @date 2017年10月11日 下午3:47:44
     * @Title: addCoupon
     * @author （guohao）
     * @version V1.0
     */
    private int addCoupon(Long couponId, YgUser user, String date) {
        long diffDayes;
        if (StringUtils.isBlank(date)) {
            diffDayes = 6L;
        } else {
            Date endDate = DateConvertUtils.parse(date, DateConvertUtils.DATE_FORMAT);
            diffDayes = DateConvertUtils.diffDayes(new Date(), endDate);
        }
        YgCoupon coupon = ygCouponService.findById(couponId);
        coupon.setPostponeDays(diffDayes + 1);
        ygCouponDetailService.usePostponeCoupon(coupon, user);
        return 1;
    }

    private Long givePrize(Integer selectId, Object[][] prizeArr, YgUser user, String baseKey) {
        Long addrId = 0L;
        String acountKey = baseKey + "_49";
        String baoKey = baseKey + "500605041";
        String xiongKey = baseKey + "123456";

        BigDecimal money = new BigDecimal(0);
        long parseLong = Long.parseLong(prizeArr[selectId][1].toString());
        if (parseLong < 100) {
            if (parseLong == 49) {
                String countStr = redisDao.get(acountKey);
                Integer count = StringUtil.isEmpty(countStr) ? 0 : Integer.parseInt(countStr);
                if (count >= 1) {
                    addrId = -1L;
                    selectId = 0;
                } else {
                    count++;
                    redisDao.set(acountKey, count + "", 24 * 60 * 60 * 1000);
                }
            }
            // 成长基金
            money = new BigDecimal(prizeArr[selectId][1].toString());

            this.addBalance(user.getId(), money);
        } else if (parseLong > 100 && parseLong < 300) {
            // 优惠券
            Long couponId = Long.parseLong(prizeArr[selectId][1].toString());

            this.addCoupon(couponId, user, "2017-12-31");

        } else if (parseLong > 400) {
            Boolean canSend = true;
            if (parseLong == 500605031L) {
                // 帆布包
                String countStr = redisDao.get(baoKey);
                Integer count = StringUtil.isEmpty(countStr) ? 0 : Integer.parseInt(countStr);

                if (count >= 5) {
                    canSend = false;
                } else {
                    count++;
                    redisDao.set(baoKey, count + "", 24 * 60 * 60 * 1000);
                }

            } else if (parseLong == 500779011L) {
                // 熊玩偶
                String countStr = redisDao.get(xiongKey);
                Integer count = StringUtil.isEmpty(countStr) ? 0 : Integer.parseInt(countStr);
                if (count >= 5) {
                    canSend = false;
                } else {
                    count++;
                    redisDao.set(xiongKey, count + "", 24 * 60 * 60 * 1000);
                }
            }
            if (canSend) {

                String skuCode = prizeArr[selectId][1].toString();

                addrId = this.addActionAddress(skuCode, prizeArr[selectId][2].toString());

            } else {
                // 超过限额，给一元成长基金
                addrId = -1L;
                this.addBalance(user.getId(), new BigDecimal(1));
            }
        }

        return addrId;
    }

    /**
     * 摇一摇
     *
     * @param callback
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "tryShare", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject tryShare(String callback) throws ParseException {
        Object[][] prizeArr = new Object[][]{
                // 里面的指针转动
                {0, 178, 98, "98元现金券", "25"}, {1, 179, 60, "60元现金券", "75"}};
        JSONPObject json = null;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        // 判断是不是新用户
        if (Objects.requireNonNull(SessionUtil.getCurrentUser()).getCreateTime().before(df.parse("2017-06-16"))) {
            json = new JSONPObject(callback, Message.error("抱歉亲，只限壹果新用户参与哦"));
            return json;
        }
        /*
         * if (currDate.after(actionDate)) { json = new JSONPObject(callback,
         * Message.error("此活动已经结束")); return json; }
         */
        String userName = SessionUtil.getCurrentUser().getUserName();
        String userKey = "try_" + userName;
        String userVal = redisDao.get(userKey);
        Integer userCount = 0;
        if (userVal == null) {
            redisDao.set(userKey, 1 + "", 8 * oneDay);
        } else {
            json = new JSONPObject(callback, Message.error("不要贪心,您已参与过活动哦"));
            return json;
        }
        YgUser user = SessionUtil.getCurrentUser();

        List<Double> orignalRates = new ArrayList<>();
        for (int i = 0; i < prizeArr.length; i++) {
            String str = (String) prizeArr[i][4];
            orignalRates.add(Double.valueOf(str));
        }
        Integer selectId = lottery(orignalRates);
        // 当命中第一个时，判断第一个已经中了多少次，大于1000时，返回第二个礼券
        if (selectId == 0) {
            String oneCountKey = "OneMoney_";
            String oneCount = redisDao.get(oneCountKey);

            int m = Integer.parseInt(oneCount == null ? "0" : oneCount) + 1;
            if (m > 500) {
                selectId = 1;
            } else {
                redisDao.set(oneCountKey, m + "", 20 * oneDay);
            }
        }

        Long couponBatchId = Long.valueOf(prizeArr[selectId][1].toString());
        ygCouponService.receiveCoupon(couponBatchId, user);
        json = new JSONPObject(callback, Message.success(generateResultMap(userCount, prizeArr[selectId][2])));

        return json;
    }

    public int lottery(List<Double> orignalRates) {
        if (orignalRates == null || orignalRates.isEmpty()) {
            return -1;
        }

        int size = orignalRates.size();

        // 计算总概率，这样可以保证不一定总概率是1
        double sumRate = 0d;
        for (double rate : orignalRates) {
            sumRate += rate;
        }

        // 计算每个物品在总概率的基础下的概率情况
        List<Double> sortOrignalRates = new ArrayList<>(size);
        Double tempSumRate = 0d;
        for (double rate : orignalRates) {
            tempSumRate += rate;
            sortOrignalRates.add(tempSumRate / sumRate);
        }

        // 根据区块值来获取抽取到的物品索引
        double nextDouble = Math.random();
        sortOrignalRates.add(nextDouble);
        Collections.sort(sortOrignalRates);

        return sortOrignalRates.indexOf(nextDouble);
    }

    // 根据概率获取奖项
    public Integer getRand(Integer obj[]) {
        Integer result = null;
        try {
            int sum = 0;// 概率数组的总概率精度
            for (int i = 0; i < obj.length; i++) {
                sum += obj[i];
            }
            for (int i = 0; i < obj.length; i++) {// 概率数组循环
                int randomNum = new Random().nextInt(sum);// 随机生成1到sum的整数
                if (randomNum < obj[i]) {// 中奖
                    result = i;
                    break;
                } else {
                    sum -= obj[i];
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private Map<String, Object> generateResultMap(Integer userCount, Object id) {
        Map<String, Object> map = new HashMap<>();
        map.put("userCount", userCount);
        map.put("id", id);
        return map;
    }

    @RequestMapping(value = "shareReward", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject shareReward(@RequestParam Long requestId, String callback) {
        Long userId = SessionUtil.getCurrentUser().getId();
        System.out.println(requestId.toString());
        YgCouponUseDetail couponUserDetail = couponUseDetailService.findCouponUseDetailByOrderId(userId, requestId.toString());
        if (couponUserDetail != null) {
            return new JSONPObject(callback, this.findCouponUseDetail(couponUserDetail));
        }

        /**
         * 线上
         */
        Object[][] prizeArr = new Object[][]{{0, 45, "单次包邮卡", "37.5"}, {1, 259, "无门槛", "42.5"}, {2, 260, "满60元可用", "20"}, {3, 261, "满60元可用", "20"}};

        /**
         * 104
         */
        /*Object[][] prizeArr = new Object[][] { { 0, 47, "单次包邮卡", "37.5" }, { 1, 250, "5元无门槛", "25" }, { 2, 251, "老用户满60减10", "37.5" }, { 3, 252, "新用户满60-20", "37.5" }};*/

        // 判断活动时间
		/*Date actionDate = new Date();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		actionDate = df.parse("2018-12-31");
		Date currDate = new Date();
		if (currDate.after(actionDate)) {
			return new JSONPObject(callback, Message.error("此活动已经结束"));
		}*/
        List<Double> orignalRates = new ArrayList<>();
        for (int i = 0; i < prizeArr.length; i++) {
            String str = (String) prizeArr[i][3];
            orignalRates.add(Double.valueOf(str));
        }
        Integer selectId = lottery(orignalRates);
        if (selectId > 3) {
            return new JSONPObject(callback, Message.error("请稍后重试", null));
        }
        YgUser user = userService.findById(SessionUtil.getCurrentUser().getId());
        Boolean newCustom = userService.isNewCustom(user.getId());

        if (user.getLevel().compareTo(10) == 0 && selectId == 0) {// 女王不可领包邮卡, 更换成商品券
            selectId = 1;
        } else if (newCustom && selectId == 2) {// 新用户不可领60-10
            selectId = 3;
        } else if (!newCustom && selectId == 3) {// 老用户不可怜60-20
            selectId = 2;
        }
        Long rewardId = Long.valueOf(prizeArr[selectId][1].toString());
        String remark = "订单分享赠券：requestId-->" + requestId;
        YgCouponUseDetail ygCouponUseDetail = new YgCouponUseDetail();
        Map<String, Object> data = new HashMap<>();
        if (selectId == 0) { // selectId为0，保存卡券
            List<YgCardCoupon> cardCouponList = ygCardCouponService.findCardsByMonth(CardType.ShareReward, CardMode.Card, null);
            if (CollectionUtils.isEmpty(cardCouponList)) {
                return new JSONPObject(callback, Message.error("请稍后重试", null));
            }
            YgCardCoupon cardCoupon = cardCouponList.get(0);
            ygCardCouponDetailService.saveCardCouponDetail(user.getId(), cardCoupon, null, requestId.toString());
            ygCouponUseDetail.setUseType(UseType.Card);
            ygCouponUseDetail.setRemark(cardCoupon.getTitle());
            data.put("price", 10);
            data.put("type", "card");
        } else {
            Message receiveCouponMsg = ygCouponDetailService.receiveCouponWithRemark(rewardId, remark, user);
            if (!receiveCouponMsg.getType().equals(Message.Type.success)) {
                return new JSONPObject(callback, receiveCouponMsg);
            }
            ygCouponUseDetail.setUseType(UseType.Coupon);
            YgCouponDetail couponDetail = (YgCouponDetail) receiveCouponMsg.getExtra();
            YgCoupon coupon = couponDetail.getCoupon();
            ygCouponUseDetail.setRemark(coupon.getCouponTitle());
            data.put("price", coupon.getFaceValue());
            data.put("type", "coupon");
        }
        Date date = new Date();
        ygCouponUseDetail.setOrderId(requestId);
        ygCouponUseDetail.setCreateTime(date);
        ygCouponUseDetail.setRelationId(rewardId);
        String string = requestId.toString();
        ygCouponUseDetail.setShareUserId(Long.valueOf(string.substring(0, string.length() - 13)));
        ygCouponUseDetail.setUserId(user.getId());
        couponUseDetailService.save(ygCouponUseDetail);
        data.put("title", ygCouponUseDetail.getRemark());
        data.put("createTime", date);
        return new JSONPObject(callback, Message.success(data));
    }

    private Message findCouponUseDetail(YgCouponUseDetail couponUserDetail) {
        Map<String, Object> data = new HashMap<>();
        if (couponUserDetail.getUseType().equals(UseType.Card)) {
            List<YgCardCouponDetail> list = ygCardCouponDetailService.findByRemark(couponUserDetail.getUserId(), couponUserDetail.getOrderId().toString(), DataStatus.Valid);
            data.put("price", 10);
            data.put("type", "card");
            data.put("useStatus", list.get(0).getUseStatus());
        } else if (couponUserDetail.getUseType().equals(UseType.Coupon)) {
            YgCoupon coupon = ygCouponService.findById(couponUserDetail.getRelationId());
            List<YgCouponDetail> list = ygCouponDetailService.findByCouponBatchId(coupon.getId(), couponUserDetail.getUserId());
            for (YgCouponDetail ygCouponDetail : list) {
                String remark = ygCouponDetail.getRemark();
                if (StringUtils.isNotBlank(remark) && remark.equals("订单分享赠券：requestId-->" + couponUserDetail.getOrderId())) {
                    data.put("price", coupon.getFaceValue());
                    data.put("type", "coupon");
                    data.put("useStatus", ygCouponDetail.getUseStatus().equals(CouponStatus.Used) ? "Used" : "UnUsed");
                    break;
                }
            }
        }
        data.put("title", couponUserDetail.getRemark());
        data.put("createTime", couponUserDetail.getCreateTime());
        return Message.success(data);
    }

    /**
     * 当前分享，领取记录
     *
     * @param requestId
     * @param callback
     * @return
     */
    @RequestMapping(value = "shareRewardList", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject shareRewardList(@RequestParam Long requestId, String callback) {
        return new JSONPObject(callback, Message.success(couponUseDetailService.findByOrderId(requestId)));
    }

}
